import { FIEngine } from '../framework/FIEngine.js';
import { FISprite } from '../framework/FISprite.js';

export class Selector extends FISprite {
  private _mouseFromX: number = 0;
  private _mouseFromY: number = 0;
  private _mouseToX: number = 0;
  private _mouseToY: number = 0;
  private _engine: FIEngine;

  constructor(engine: FIEngine) {
    super();
    this.visible = false;
    this._engine = engine;
    const mcb = engine.createMouse();
    mcb.onLBDown = ({ x, y }) => this.mouseDown(x, y);
    mcb.onLBMove = ({ x, y }) => this.mouseMove(x, y);
    mcb.onLBUp = ({ x, y }) => this.mouseUp(x, y);
    this._engine.canvas.addEventListener('mousedown', () => {
      this._engine.canvas.requestPointerLock();
      // this._engine.canvas.requestFullscreen();
    })


  }
  mouseDown(x: number, y: number) {
    this._mouseFromX = x;
    this._mouseFromY = y;
    this._mouseToX = x;
    this._mouseToY = y;
    this.visible = true;
    this.move(x, y);
    this.resize(0, 0);
  }
  mouseMove(x: number, y: number) {
    this._mouseToX = x;
    this._mouseToY = y;
    const l = Math.min(this._mouseToX, this._mouseFromX);
    const t = Math.min(this._mouseToY, this._mouseFromY);
    const r = Math.max(this._mouseToX, this._mouseFromX);
    const b = Math.max(this._mouseToY, this._mouseFromY);
    this.move(l, t);
    this.resize(r - l, b - t);
  }
  mouseUp(x: number, y: number) {
    this.visible = false;
  }
  draw(ctx: CanvasRenderingContext2D): void {
    ctx.lineWidth = 1
    ctx.strokeStyle = "#055505";
    ctx.strokeRect(+0.5, +0.5, this._w, this._h)

    ctx.lineWidth = 1
    ctx.strokeStyle = "#11CC11";
    ctx.strokeRect(-0.5, -0.5, this._w, this._h)
  }
}
